import 'dart:math';

import 'package:flutter/material.dart';

class DirectionArrowPage extends StatefulWidget {
  const DirectionArrowPage({super.key});

  @override
  State<DirectionArrowPage> createState() => _DirectionArrowPageState();
}

class _DirectionArrowPageState extends State<DirectionArrowPage> {
  // 存储滑动角度（弧度），初始值为null表示无滑动
  double? _swipeAngle;
  Offset? _startPosition;

  // 处理滑动开始
  void _handleDragStart(DragStartDetails details) {
    _startPosition = details.globalPosition;
  }

  // 处理滑动结束
  void _handleDragEnd(DragEndDetails details) {
    _startPosition = null;
  }

  // 处理滑动更新，实时计算角度
  void _handleDragUpdate(DragUpdateDetails details) {
    if (_startPosition != null) {
      // 计算滑动偏移
      final dx = details.globalPosition.dx - _startPosition!.dx;
      final dy = details.globalPosition.dy - _startPosition!.dy;

      // 计算滑动距离（确保有足够的滑动距离才更新角度）
      final distance = sqrt(dx * dx + dy * dy);

      if (distance > 20) {
        // 滑动超过20像素才响应
        // 计算角度（弧度）
        setState(() {
          _swipeAngle = atan2(dy, dx);
        });
      }
    }
  }

  // 将弧度转换为方向文本
  String _getDirectionText() {
    if (_swipeAngle == null) {
      return '在屏幕上任意方向滑动';
    }

    // 将弧度转换为角度（0-360）
    final degrees = (_swipeAngle! * 180 / pi) % 360;

    if ((degrees >= 337.5) || (degrees < 22.5)) {
      return '右';
    } else if (degrees < 67.5) {
      return '右下';
    } else if (degrees < 112.5) {
      return '下';
    } else if (degrees < 157.5) {
      return '左下';
    } else if (degrees < 202.5) {
      return '左';
    } else if (degrees < 247.5) {
      return '左上';
    } else if (degrees < 292.5) {
      return '上';
    } else {
      return '右上';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('任意方向滑动箭头'),
      ),
      body: GestureDetector(
        // 监听滑动事件
        onPanStart: _handleDragStart,
        onPanUpdate: _handleDragUpdate,
        onPanEnd: _handleDragEnd,
        child: Container(
          color: Colors.white,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const SizedBox(height: 40),
                // 箭头绘制区域
                SizedBox(
                  width: 200,
                  height: 200,
                  child: CustomPaint(
                    painter: ArrowPainter(
                      angle: _swipeAngle,
                      color: Colors.blue,
                    ),
                  ),
                ),
                const SizedBox(height: 30),
                // 显示当前方向文本
                Text(
                  _getDirectionText(),
                  style: const TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 20),
                if (_swipeAngle != null)
                  Text(
                    '角度: ${(_swipeAngle! * 180 / pi).toStringAsFixed(1)}°',
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.grey,
                    ),
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

// 自定义绘制任意方向箭头的Painter
class ArrowPainter extends CustomPainter {
  final double? angle; // 箭头方向角度（弧度）
  final Color color;

  ArrowPainter({
    this.angle,
    required this.color,
  });

  @override
  void paint(Canvas canvas, Size size) {
    if (angle == null) {
      // 初始状态绘制提示圆圈
      final paint = Paint()
        ..color = Colors.grey[200]!
        ..style = PaintingStyle.stroke
        ..strokeWidth = 2;

      canvas.drawCircle(
        Offset(size.width / 2, size.height / 2),
        size.width / 2 - 10,
        paint,
      );
      return;
    }

    final paint = Paint()
      ..color = color
      ..style = PaintingStyle.fill;

    // 箭头大小参数
    final arrowLength = 50;
    final arrowWidth = 2;
    final arrowHeadLength = 10.0;

    // 中心点（箭头旋转中心）
    // final center = Offset(size.width / 2, size.height / 2);

    // 保存当前画布状态
    canvas.save();

    // 移动原点到中心
    // canvas.translate(center.dx, center.dy);

    // 旋转画布（角度加上π/2是为了让0度指向右侧）
    canvas.rotate(angle!);

    // 绘制箭头路径
    final path = Path();
    // 箭头尾部
    path.moveTo(-arrowLength + arrowHeadLength, 0);
    path.lineTo(-arrowLength + arrowHeadLength, arrowWidth / 2);
    path.lineTo(0, arrowWidth / 2);
    path.lineTo(arrowHeadLength, 0);
    path.lineTo(0, -arrowWidth / 2);
    path.lineTo(-arrowLength + arrowHeadLength, -arrowWidth / 2);
    path.lineTo(-arrowLength + arrowHeadLength, 0);
    path.close();

    canvas.drawPath(path, paint);

    // 恢复画布状态
    canvas.restore();

    // 绘制中心点
    // canvas.drawCircle(
    //   center,
    //   5,
    //   Paint()..color = Colors.black,
    // );
  }

  // 当角度改变时重绘
  @override
  bool shouldRepaint(covariant ArrowPainter oldDelegate) {
    return oldDelegate.angle != angle || oldDelegate.color != color;
  }
}
